package com.padgett.resourcemanagement.client;

import java.io.IOException;
import java.util.Date;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;
import com.padgett.resourcemanagement.data.ClientDAO;

/**
 * Save client.  Extra logic is to mark this client as incomplete.
 * 
 * @author andyleung
 * 
 */
@SuppressWarnings("serial")
public class SavePersonalClientServlet extends HttpServlet{
	private static final Logger log=Logger.getLogger(SavePersonalClientServlet.class.getName());
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		String id=req.getParameter("clientId");
		String clientNumber=req.getParameter("ClientNumber");
		String firstName=req.getParameter("FirstName");
		String lastName=req.getParameter("LastName");
		String name=firstName+" "+lastName;
		String homePhone=req.getParameter("HomePhone");
		String cellPhone=req.getParameter("CellPhone");
		String workPhone=req.getParameter("WorkPhone");
		String feeCollectedString=req.getParameter("FeeCollected");
		String email=req.getParameter("Email");
		String accountant=req.getParameter("Accountant");
		String numberOfReturnsString=req.getParameter("NumberOfReturns");
		String numberOfReturnsCompletedString=req.getParameter("NumberOfReturnsCompleted");
		String numberOfReturnsSignedString=req.getParameter("NumberOfReturnsSigned");
		String dateInString=req.getParameter("DateIn");
		String dateCompletedString=req.getParameter("DateCompleted");
		String numberOfReturnsEFiledString=req.getParameter("NumberOfReturnsEFiled");
		String dateEFiledString=req.getParameter("DateEFiled");
		String numberOfReturnsPaperFiledString=req.getParameter("NumberOfReturnsPaperFiled");
		String dateFiledString=req.getParameter("DateFiled");
		String feeString=req.getParameter("Fee");
		String dateCollectedString=req.getParameter("DateCollected");
		String methodOfPayment=req.getParameter("MethodOfPayment");
		String note=req.getParameter("Note");
		// Client Number and Legal Number must be presented to generate a unique key
		UserService userService=UserServiceFactory.getUserService();
		User user=userService.getCurrentUser();
		Key key=null;
		Entity client=null;
		String nickname=null;
		if(user!=null&&user.getNickname()!=null){
			nickname=user.getNickname();
		}else{
			if(accountant!=null){
				Entity acctant=ClientDAO.loadEntity(KeyFactory.stringToKey(accountant));
				if(acctant!=null){
					nickname=(String)acctant.getProperty("Nickname");
				}
			}
		}
		if(id==null||id.isEmpty()){
			key=new KeyFactory.Builder("PersonalClient",clientNumber).getKey();
			client=new Entity(key);
			client.setProperty("CreatedBy", nickname);
			client.setProperty("CreatedDate", new Date(System.currentTimeMillis()));
			client.setProperty("LastModifiedBy", nickname);
			client.setProperty("LastModifiedDate", new Date(System.currentTimeMillis()));
		}else{
			key=KeyFactory.stringToKey(id);
			client=ClientDAO.loadEntity(key);
			client.setProperty("LastModifiedBy", nickname);
			client.setProperty("LastModifiedDate", new Date(System.currentTimeMillis()));
		}
		client.setProperty("ClientNumber", clientNumber);
		client.setProperty("NameSearch", name.toLowerCase());
		client.setUnindexedProperty("Name", name);
		client.setUnindexedProperty("FirstName", firstName);
		client.setProperty("LastName", lastName);
		// If EFILE+PFFILE < # of Return, incomplete
		int numberOfReturns=0;
		try{
			numberOfReturns=Integer.parseInt(numberOfReturnsString);
		}catch(NumberFormatException nfe){
			numberOfReturns=0;
		}
		int numberOfReturnsCompleted=0;
		try{
			numberOfReturnsCompleted=Integer.parseInt(numberOfReturnsCompletedString);
		}catch(NumberFormatException nfe){
			numberOfReturnsCompleted=0;
		}
		int numberOfReturnsSigned=0;
		try{
			numberOfReturnsSigned=Integer.parseInt(numberOfReturnsSignedString);
		}catch(NumberFormatException nfe){
			numberOfReturnsSigned=0;
		}
		int numberOfReturnsEFiled=0;
		try{
			numberOfReturnsEFiled=Integer.parseInt(numberOfReturnsEFiledString);
		}catch(NumberFormatException nfe){
			numberOfReturnsEFiled=0;
		}
		int numberOfReturnsPaperFiled=0;
		try{
			numberOfReturnsPaperFiled=Integer.parseInt(numberOfReturnsPaperFiledString);
		}catch(NumberFormatException nfe){
			numberOfReturnsPaperFiled=0;
		}
		double fee=0;
		try{
			fee=Integer.parseInt(feeString);
		}catch(NumberFormatException nfe){
			fee=0;
		}
		double feeCollected=0;
		try{
			feeCollected=Integer.parseInt(feeCollectedString);
		}catch(NumberFormatException nfe){
			feeCollected=0;
		}
		client.setProperty("AllFiled", (numberOfReturns==(numberOfReturnsEFiled+numberOfReturnsPaperFiled)?true:false));
		client.setUnindexedProperty("HomePhone", homePhone);
		client.setUnindexedProperty("CellPhone", cellPhone);
		client.setUnindexedProperty("WorkPhone", workPhone);
		client.setUnindexedProperty("Email", email);
		client.setUnindexedProperty("NumberOfReturns", numberOfReturns);
		client.setUnindexedProperty("NumberOfReturnsCompleted", numberOfReturnsCompleted);
		client.setUnindexedProperty("NumberOfReturnsSigned", numberOfReturnsSigned);
		client.setUnindexedProperty("NumberOfReturnsEFiled", numberOfReturnsEFiled);
		client.setUnindexedProperty("NumberOfReturnsPaperFiled", numberOfReturnsPaperFiled);
		client.setUnindexedProperty("Fee", fee);
		client.setUnindexedProperty("FeeCollected", feeCollected);
		client.setUnindexedProperty("MethodOfPayment", methodOfPayment);
		client.setProperty("Accountant", accountant);
		Date dateIn=null;
		if(dateInString!=null&&!dateInString.isEmpty()){
			dateIn = new Date(Long.parseLong(dateInString));
			client.setProperty("DateIn", dateIn);
		}
		Date dateCompleted=null;
		if(dateCompletedString!=null&&!dateCompletedString.isEmpty()){
			dateCompleted = new Date(Long.parseLong(dateCompletedString));
			client.setProperty("DateCompleted", dateCompleted);
		}
		Date dateEFiled=null;
		if(dateEFiledString!=null&&!dateEFiledString.isEmpty()){
			dateEFiled = new Date(Long.parseLong(dateEFiledString));
			client.setProperty("DateEFiled", dateEFiled);
		}
		Date dateFiled=null;
		if(dateFiledString!=null&&!dateFiledString.isEmpty()){
			dateFiled = new Date(Long.parseLong(dateFiledString));
			client.setProperty("DateFiled", dateFiled);
		}
		Date dateCollected=null;
		if(dateCollectedString!=null&&!dateCollectedString.isEmpty()){
			dateCollected = new Date(Long.parseLong(dateCollectedString));
			client.setProperty("DateCollected", dateCollected);
		}
		if(note!=null){
			client.setProperty("Note", new Text(note));
		}
		Key savedKey=ClientDAO.saveEntity(client);
		JSONObject response=new JSONObject();
		try {
			if(savedKey!=null){
				response.put("success", "true");
				response.put("clientId", KeyFactory.keyToString(savedKey));
			}else{
				response.put("success", "false");
				response.put("error", "Unable to save client at the moment.");
			}
		} catch (JSONException e) {
			log.severe(e.getMessage());
		}
		resp.getWriter().write(response.toString());
	}

}
